﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace SharePointUtilitiesForDevelopers.Mapper
{
    /// <summary>
    /// A mapper that maps the xml web service response to a <see cref="SharePointListItem"/>.
    /// </summary>
    public class SharePointListItemMapper: IMapper<XElement, SharePointListItem>
    {

        /// <summary>
        /// Maps the source type to the target type.
        /// </summary>
        /// <param name="from">The object to map from.</param>
        /// <returns>The mapped object.</returns>
        public SharePointListItem Map(XElement from)
        {
            return MapList(from).SingleOrDefault();
        }

        /// <summary>
        /// Maps the source type to a list of the target type.
        /// </summary>
        /// <param name="from">From.</param>
        /// <returns></returns>
        public IEnumerable<SharePointListItem> MapList(XElement from)
        {
            try
            {
                var lists = SharePointMapper.MapResponseToList<SharePointListItem>(
                    MapInternal,
                    ele => string.Compare(ele.Name.LocalName, "row", StringComparison.InvariantCultureIgnoreCase) == 0,
                    from);

                return lists.ToList();
            }
            catch (Exception ex)
            {
                throw new SharePointMapperException<XElement, SharePointListItem>(ex);
            }
        }

        /// <summary>
        /// Maps the element to a domain object.
        /// </summary>
        /// <param name="element">The element to map from.</param>
        /// <returns>The mapped object.</returns>
        private static SharePointListItem MapInternal(XElement element)
        {
            var listItem = new SharePointListItem
                       {
                           Definition = element,
                           Id = SharePointXml.GetAttributeAsString(element, "ows_ID"),
                           Title = SharePointXml.GetAttributeAsString(element, "ows_Title")
                       };

            // Create a dictionary of field values
            var values = new Dictionary<string, string>();

            foreach(var attr in element.Attributes())
            {
                values.Add(attr.Name.LocalName.Replace("ows_", ""), attr.Value);
            }

            // Set the values
            listItem.Values = values;

            return listItem;
        }
    }
}